package com.xqboss.apps.service.punch;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xqboss.apps.domain.punch.PunchWeakenConfig;
import com.xqboss.apps.mapper.punch.PunchWeakenConfigMapper;
import com.xqboss.common.exception.ServiceException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Trent
 * @date 2023/8/25
 */
@Service
public class PunchWeakenConfigService extends ServiceImpl<PunchWeakenConfigMapper, PunchWeakenConfig> {

    /**
     * 设置打卡收益衰减
     * @param configs
     */
    @Transactional(rollbackFor = Exception.class)
    public void setConfig(List<PunchWeakenConfig> configs){
        // 清空所有配置
        baseMapper.removeAllByDel();
        ArrayList<PunchWeakenConfig> configsCopy = new ArrayList<>(configs);
        for (PunchWeakenConfig config : configs) {
            configsCopy.remove(config);
            for (PunchWeakenConfig item : configsCopy) {
                if(item.getDurabilityRate().doubleValue() < config.getDurabilityRate().doubleValue()){
                    if(item.getIncomeRate().doubleValue() > config.getIncomeRate().doubleValue()){
                        throw new ServiceException("配置错误！");
                    }
                }else if(item.getDurabilityRate().doubleValue() > config.getDurabilityRate().doubleValue()){
                    if(item.getIncomeRate().doubleValue() < config.getIncomeRate().doubleValue()){
                        throw new ServiceException("配置错误！");
                    }
                }else{
                    throw new ServiceException("已经存在相同耐久度配置！");
                }
            }
        }
        boolean saved = saveBatch(configs);
        if(!saved){
            throw new ServiceException("操作失败！");
        }
    }

    public List<PunchWeakenConfig> getConfigList(){
        return list(new LambdaQueryWrapper<PunchWeakenConfig>()
                .orderByDesc(PunchWeakenConfig::getDurabilityRate));
    }

    /**
     * 根据打卡配置获取
     * @param durabilityRate
     * @return
     */
    public PunchWeakenConfig getPunchWeakenConfig(BigDecimal durabilityRate){
        // 大于等于当前耐久度的最小耐久度限制
        // 如：当前耐久度为80， 配置里有90、80、70， 则取80
        return getOne(new LambdaQueryWrapper<PunchWeakenConfig>()
                .ge(PunchWeakenConfig::getDurabilityRate, durabilityRate)
                .orderByAsc(PunchWeakenConfig::getDurabilityRate)
                .last("LIMIT 1"));
    }

}
